<template>
  <div>
    <div class="search">
      <input v-model="keyword" type="text" class="input-search" placeholder="输入城市名或拼音">
    </div>
    <div class="search-content" ref="search" v-show="keyword">
      <ul>
        <li v-for="item of list"
            class="search-item border-bottom"
            @click="handleCityClick(item.name)"
        >{{item.name}}
        </li>
        <li class="search-item border-bottom"
            v-show="hasNoData"
        >搜索的数据不存在
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
  import Bscroll from 'better-scroll'
  import {mapState, mapMutations} from 'vuex'
  export default {
    name: "Search",
    props: {
      cities: Object
    },
    data() {
      return {
        keyword: '',
        list: [],
        timer: null
      }
    },
    methods: {
      handleCityClick(city) {
        //  直接调用store里的changeCity
        this.changeCity(city)
        //  跳转到首页
        this.$router.push('/')
      },
      //  扩展，把store里的changeCity传过来
      ...mapMutations(['changeCity'])
    },
    mounted() {
      this.scroll = new Bscroll(this.$refs.search)
    },
    computed:{
      hasNoData(){
        return !this.list.length
      }
    },
    watch: {
      keyword() {
        //  清除定时器
        if (this.timer) {
          clearTimeout(this.timer)
        }
        //  如果输入框没内容，搜索显示框清空
        if(!this.keyword){
          this.list = []
          return
        }
        this.timer = setTimeout(() => {
          const result = []
          for (let i in this.cities) {
            //  如果输入框的内容符合城市的拼音或者汉字，放入返回数组
            this.cities[i].forEach((value) => {
              if (value.spell.indexOf(this.keyword) > -1 ||
                value.name.indexOf(this.keyword) > -1) {
                result.push(value)
              }
            })
          }
          this.list = result
        }, 100)
      }
    }
  }
</script>

<style lang="stylus" scoped>
  @import "~styles/varible.styl"
  .search
    height: .72rem
    padding: 0 .1rem
    background: $bgColor

    .input-search
      width: 100%
      border-radius: 0.1rem
      text-align: center
      height: .62rem
      line-height: .62rem
      color: #666
      box-sizing: border-box

  .search-content
    background: #fff
    top: 1.58rem
    bottom: 0
    left: 0
    right: 0
    z-index: 1
    position: absolute
    overflow: hidden

    .search-item
      line-height: .62rem
      padding-left: .2rem
      background: #fff
      color: #666
</style>
